package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"xinhua_book/cache"
	"xinhua_book/models"
)

type CollectionController struct {
	beego.Controller
}

func (c *CollectionController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	userId, _ := c.GetInt("user_id", 1)
	var bookId []interface{}
	models.DB.Model(&models.Collection{}).Select("book_id").Where("user_id = ?", userId).Find(&bookId)
	fmt.Println(userId, bookId)
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	models.DB.Model(&models.Book{}).Where("id in (?)", bookId).Count(&count)
	sumpage := int(math.Ceil(float64(count) / float64(size)))
	if page > sumpage {
		page = sumpage
	}
	offset := (page - 1) * size
	var books []models.Book

	cacheData := cache.Rdb.Get(cache.Ctx, "collect_list").Val()
	if cacheData == "" {
		models.DB.Model(&models.Book{}).Where("id in (?)", bookId).Limit(size).Offset(offset).Find(&books)
		jsonData, _ := json.Marshal(books)
		cache.Rdb.Set(cache.Ctx, "collects_list", jsonData, 0)
	} else {
		json.Unmarshal([]byte(cacheData), &books)
	}
	c.Data["json"] = PageResponse{
		Code:    200,
		Msg:     "展示成功",
		Data:    books,
		Page:    page,
		Size:    size,
		Count:   count,
		Sumpage: sumpage,
	}
	c.ServeJSON()
	return
}
func (c *CollectionController) Del() {
	userId, _ := c.GetInt("user_id")
	bookId, _ := c.GetInt("book_id")
	if userId < 1 || bookId < 1 {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "参数错误",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	var status string
	models.DB.Model(&models.Collection{}).Select("status").Where("user_id = ? and book_id = ?", userId, bookId).Find(&status)
	if status == "已交易" {
		c.Data["json"] = Response{
			Code: 500,
			Msg:  "已完成交易，禁止删除",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		err := models.DB.Model(&models.Collection{}).Select("status").Where("user_id = ? and book_id = ?", userId, bookId).Delete(&models.Collection{}).Error
		if err != nil {
			c.Data["json"] = Response{
				Code: 500,
				Msg:  "删除失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		}
		c.Data["json"] = Response{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
}
